package com.tech.doggtv.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.baidu.cyberplayer.core.BMediaController;
import com.baidu.cyberplayer.core.BVideoView;
import com.baidu.cyberplayer.core.BVideoView.OnCompletionListener;
import com.baidu.cyberplayer.core.BVideoView.OnCompletionWithParamListener;
import com.baidu.cyberplayer.core.BVideoView.OnErrorListener;
import com.baidu.cyberplayer.core.BVideoView.OnInfoListener;
import com.baidu.cyberplayer.core.BVideoView.OnPlayingBufferCacheListener;
import com.baidu.cyberplayer.core.BVideoView.OnPreparedListener;
import com.tech.doggtv.R;
import com.tech.doggtv.action.EventType;
import com.tech.doggtv.action.ProgramsAction;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.Process;
import android.os.PowerManager.WakeLock;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import de.greenrobot.event.EventBus;

/**
 * 首页，视频播放页面
 */
public class VideoViewPlayingActivity extends AppCompatActivity implements OnPreparedListener,
                            OnCompletionListener,
                            OnErrorListener, 
                            OnInfoListener,
                            OnPlayingBufferCacheListener,
                            OnCompletionWithParamListener{
    private final String TAG = VideoViewPlayingActivity.class.getSimpleName();
    
	/**
     * 您的AK 
     * 请到http://console.bce.baidu.com/iam/#/iam/accesslist获取
     */
    private String AK = "4053b4cb7fdf45f7b53feea58198bec4";  // 请录入您的AK !!!
        
    private String mVideoSource = null;
    
    private BVideoView mVV = null;
    private BMediaController mVVCtl = null;
    private RelativeLayout mViewHolder = null;
    private LinearLayout mControllerHolder = null;
    
//    private boolean mIsHwDecode = false;
    
    private EventHandler mEventHandler;
    private HandlerThread mHandlerThread;
    
    private final Object SYNC_Playing = new Object();
        
    private final int EVENT_PLAY = 0;
    private static final int UI_EVENT_TAKESNAPSHOT = 2;

    private WakeLock mWakeLock = null;
    private static final String POWER_LOCK = "VideoViewPlayingActivity";
    private Toast toast;
    private long firstBackTime, betTime = 1500;
    private boolean isActionDown;

    /**
     * 播放状态
     */
    private  enum PLAYER_STATUS {
        PLAYER_IDLE, PLAYER_PREPARING, PLAYER_PREPARED,
    }
    
    private PLAYER_STATUS mPlayerStatus = PLAYER_STATUS.PLAYER_IDLE;
    
    
    /**
     * 记录播放位置
     */
    private int mLastPos = 0;
    //播放的文件列表
    private File[] programs;
    //循环播放时候的节目位置
    private int mCurrentProgPos;
    //是否循环播放
    private boolean isLoopPaly = true;
    private boolean isAutoPlayNext = true;

    
    class EventHandler extends Handler {
        public EventHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case EVENT_PLAY:
                if(TextUtils.isEmpty(mVideoSource)){
                    break;
                }
                /**
                 * 如果已经播放了，等待上一次播放结束
                 */
                if (mPlayerStatus != PLAYER_STATUS.PLAYER_IDLE) {
                    synchronized (SYNC_Playing) {
                        try {
                            SYNC_Playing.wait();
                            Log.v(TAG, "wait player status to idle");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

                /**
                 * 设置播放url
                 */

                mVV.setVideoPath(mVideoSource);
               // mVV.setVideoScalingMode(BVideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT);
                /**
                 * 续播，如果需要如此
                 */
                if (mLastPos > 0) {

                    mVV.seekTo(mLastPos);
                    mLastPos = 0;
                }

                /**
                 * 显示或者隐藏缓冲提示 
                 */
                mVV.showCacheInfo(true);
                
                /**
                 * 开始播放
                 */
                mVV.start();

                mPlayerStatus = PLAYER_STATUS.PLAYER_PREPARING;
                break;
            case UI_EVENT_TAKESNAPSHOT:
                boolean sdCardExist = isExternalStorageWritable();
                File sdDir = null;
                String strpath = null;
                Bitmap bitmap = null;
                Date date = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSSS");
                String time = formatter.format(date);
                Log.i(TAG, "sdcardExist="+sdCardExist);
                if (sdCardExist){
                    sdDir = Environment.getExternalStorageDirectory();
                    // check the dir is existed or not!.
                    //File file = new File(sdDir.toString());
                    strpath = sdDir.toString()+"/" + time + ".jpg";
                }else{
                    strpath = "/data/data/" + "/" + time + ".jpg";
                }
                Log.e(TAG, "snapshot save path="+strpath);

                bitmap = mVV.takeSnapshot();
                if (bitmap != null){
                    FileOutputStream os = null;
                    try {
                        os = new FileOutputStream(strpath, false);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                        os.flush();
                        os.close();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    } finally {
                        if (os != null)
                            try {
                                os.close();
                            } catch (Throwable t) {
                            }
                    }
                    os = null;
                }

                if (toast == null){
                    toast = Toast.makeText(VideoViewPlayingActivity.this, strpath, Toast.LENGTH_SHORT);
                }else{
                    toast.setText(strpath);
                }
                toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
                toast.show();

                break;
            default:
                break;
            }
        }
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
        }
        return false;
    }

    /**
     * 实现切换示例
     */
    private OnClickListener mPreListener = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            Log.v(TAG, "pre btn clicked");
            prePaly();
        }
    };

    /**
     * 重新播放
     */
    private void prePaly(){
        /**
         * 如果已经开发播放，先停止播放
         */
        if(mPlayerStatus != PLAYER_STATUS.PLAYER_IDLE){
            mVV.stopPlayback();
        }

        /**
         * 发起一次新的播放任务
         */
        if(mEventHandler.hasMessages(EVENT_PLAY))
            mEventHandler.removeMessages(EVENT_PLAY);
        mEventHandler.sendEmptyMessage(EVENT_PLAY);
    }
    
    private OnClickListener mNextListener = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            Log.v(TAG, "next btn clicked");
        }
    };

    private OnClickListener mSnapshotListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            //mVV.takeSnapshot(null);
            mEventHandler.sendEmptyMessage(UI_EVENT_TAKESNAPSHOT);
            Log.v(TAG, "Snapshot clicked");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.controllerplaying);
        EventBus.getDefault().register(this);
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, POWER_LOCK);
        
//        mIsHwDecode = getIntent().getBooleanExtra("isHW", false);
//        Uri uriPath = getIntent().getData();

        getPlayProgram();
        initUI();
        /**
         * 开启后台事件处理线程
         */
        mHandlerThread = new HandlerThread("event handler thread",
                Process.THREAD_PRIORITY_BACKGROUND);
        mHandlerThread.start();
        mEventHandler = new EventHandler(mHandlerThread.getLooper());
    }

    /**
     *点击选择界面列表的时候，回掉播放某个影片
     */
    public void onEventMainThread(EventType eventType){
        Log.v(TAG, eventType+" is null");
        if(eventType!=null) {
            Log.v(TAG, eventType.currentPos+","+eventType.files.length);
            programs = eventType.files;
            mCurrentProgPos = eventType.currentPos;
            changeProgram(mCurrentProgPos);
            mLastPos = 0;
            prePaly();
        }
    }

    /**
     * 得到当前播放的的节目列表
     */
    private void getPlayProgram(){
        programs = ProgramsAction.getPrograms("1");
        if(programs.length>0){
            Uri uriPath = Uri.parse(programs[0].getAbsolutePath());
            if (null != uriPath) {
                String scheme = uriPath.getScheme();
                if (null != scheme) {
                    mVideoSource = uriPath.toString();
                } else {
                    mVideoSource = uriPath.getPath();
                }

            }
        }

    }

    /**
     * 切换节目播放
     * @param pos
     */
    private void changeProgram(int pos){
        if(programs.length>0){
            Uri uriPath = Uri.parse(programs[pos].getAbsolutePath());
            if (null != uriPath) {
                String scheme = uriPath.getScheme();
                if (null != scheme) {
                    mVideoSource = uriPath.toString();
                } else {
                    mVideoSource = uriPath.getPath();
                }

            }
        }
    }

    /**
     * 播放下一集
     */
    private void nextPlay(){
        if(isAutoPlayNext){
            int programNumb = programs.length;
            mCurrentProgPos = ProgramsAction.getNextPlayPos(mCurrentProgPos, programNumb);
            changeProgram(mCurrentProgPos);
            mLastPos = 0;
            prePaly();
        }
    }


    /**
     * 初始化界面
     */
    private void initUI() {        
        mViewHolder = (RelativeLayout)findViewById(R.id.view_holder);
        mControllerHolder = (LinearLayout )findViewById(R.id.controller_holder);
        
        /**
         * 设置ak
         */
        BVideoView.setAK(AK);
        
        /**
         *创建BVideoView和BMediaController
         */
        mVV = new BVideoView(this);
        mVVCtl = new BMediaController(this);
        mViewHolder.addView(mVV);
        mControllerHolder.addView(mVVCtl);
        /**
         * 注册listener
         */
        mVV.setOnPreparedListener(this);
        mVV.setOnCompletionListener(this);
        mVV.setOnCompletionWithParamListener(this);
        mVV.setOnErrorListener(this);
        mVV.setOnInfoListener(this);
        mVVCtl.setPreNextListener(mPreListener, mNextListener);
        mVVCtl.setSnapshotListener(mSnapshotListener);
        /**
         * 关联BMediaController
         */
        mVV.setMediaController(mVVCtl);
//disable dolby audio effect
//        mVV.setEnableDolby(false);
        /**
         * 设置解码模式
         */
        mVV.setDecodeMode(BVideoView.DECODE_SW);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.v(TAG, "onPause");
        /**
         * 在停止播放前 你可以先记录当前播放的位置,以便以后可以续播
         */
        if (mVV.isPlaying() && (mPlayerStatus != PLAYER_STATUS.PLAYER_IDLE)) {
            mLastPos = (int) mVV.getCurrentPosition();
            //when scree lock,paus is good select than stop
            // don't stop pause
            // mVV.stopPlayback();
            mVV.pause();
        }    
    }

    
    @Override
    protected void onResume() {
        super.onResume();
        Log.v(TAG, "onResume");
        if (null != mWakeLock && (!mWakeLock.isHeld())) {
            mWakeLock.acquire();
        }
        // 发起一次播放任务,当然您不一定要在这发起
        if (!mVV.isPlaying() && (mPlayerStatus != PLAYER_STATUS.PLAYER_IDLE)) {
            mVV.resume();
        } else {
            mEventHandler.sendEmptyMessage(EVENT_PLAY);
        }
    }
    
    @Override
    protected void onStop(){
        super.onStop();
        Log.v(TAG, "onStop");
        // 在停止播放前 你可以先记录当前播放的位置,以便以后可以续播
        if (mVV.isPlaying() && (mPlayerStatus != PLAYER_STATUS.PLAYER_IDLE)) {
            mLastPos = (int) mVV.getCurrentPosition();
            // don't stop pause
            // mVV.stopPlayback();
            mVV.pause();
        }
        if (toast != null){
            toast.cancel();
        }
    }
    
    @Override
    protected void onDestroy(){
        super.onDestroy();
        if ((mPlayerStatus != PLAYER_STATUS.PLAYER_IDLE)) {
            mLastPos = (int) mVV.getCurrentPosition();
            mVV.stopPlayback();
        }
        if(toast != null){
            toast.cancel();
        }
        /**
         * 结束后台事件处理线程
         */
        mHandlerThread.quit();
        EventBus.getDefault().unregister(this);
        Log.v(TAG, "onDestroy");
    }

    @Override
    public boolean onInfo(int what, int extra) {
        switch(what){
        /**
         * 开始缓冲
         */
        case BVideoView.MEDIA_INFO_BUFFERING_START:
            Log.i(TAG,
                    "caching start,now playing url : "
                            + mVV.getCurrentPlayingUrl());

            break;
        /**
         * 结束缓冲
         */
        case BVideoView.MEDIA_INFO_BUFFERING_END:
            Log.i(TAG,
                    "caching start,now playing url : "
                            + mVV.getCurrentPlayingUrl());

            break;
        default:
            break;
        }
        return false;
    }
    
    /**
     * 当前缓冲的百分比， 可以配合onInfo中的开始缓冲和结束缓冲来显示百分比到界面
     */
    @Override
    public void onPlayingBufferCache(int percent) {
        
    }    

    /**
     * 播放出错
     */
    @Override
    public boolean onError(int what, int extra) {
        Log.v(TAG, "onError");
        synchronized (SYNC_Playing) {
            SYNC_Playing.notify();
        }
        mPlayerStatus = PLAYER_STATUS.PLAYER_IDLE;
        return true;
    }

    /**
     * 播放完成
     */
    @Override
    public void onCompletion() {
        Log.v(TAG, "onCompletion");
        
        synchronized (SYNC_Playing) {
            SYNC_Playing.notify();
        }
        mPlayerStatus = PLAYER_STATUS.PLAYER_IDLE;


    }

    /**
     * 播放准备就绪
     */
    @Override
    public void onPrepared() {
        Log.v(TAG, "onPrepared");                
        mPlayerStatus = PLAYER_STATUS.PLAYER_PREPARED;
    }
    @Override

    public void OnCompletionWithParam(int param) {
//param = 307 is end of stream
        Log.v(TAG, "OnCompletionWithParam=" + param);
        if(param == 307){
            nextPlay();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            onPause();
            Intent intent = new Intent(VideoViewPlayingActivity.this,VideoListActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
//            if(isActionDown){
//                getSupportActionBar().show();
//            }else{
//                getSupportActionBar().hide();
//
//            }
            isActionDown = !isActionDown;
        }
        return super.onTouchEvent(event);
    }


    /**
     * 退出应用程序
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstBackTime > betTime) {//如果两次按键时间间隔大于800毫秒，则不退出
                Toast.makeText(VideoViewPlayingActivity.this, R.string.exit_app_toast,
                        Toast.LENGTH_SHORT).show();
                firstBackTime = secondTime;//更新firstTime
                return false;
            } else {
                finish();
                System.exit(0);//否则退出程序
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
